package com.rovinj_server.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.rovinj_server.R;
import com.rovinj_server.adapter.FragmentTaskAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventoryTask;
import com.rovinj_server.entity.InventoryTaskSub;
import com.rovinj_server.entity.SubInfo;
import com.rovinj_server.ui.KFDActivity;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/5/11.
 */

public class TaskFragment extends Fragment {
    Socket socket = null;
    String buffer = "";
    @Bind(R.id.list_view)
    ListView mListView;
    @Bind(R.id.butt_huoqu)
    Button mButtHuoqu;
    @Bind(R.id.but_lingqu)
    Button mButLingqu;
    private View mView;
    private int checkNum; // 记录选中的条目数量
    private String mCode;
    private FragmentTaskAdapter mAdapter;

    private String mMStr;
    private List<InventoryTask> mTaskList = new ArrayList<>();
    private List<InventoryTaskSub> mTaskSubList = new ArrayList<>();
    private Context mContext;
    private DBManager mManager;
    private OutputStream mOu;
    private List<InventoryTask> mListData;
    private String mId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = View.inflate(getActivity(), R.layout.fragment_task, null);
        }
        ButterKnife.bind(this, mView);
        ini();//初始化
        initView();
        iniThread();
        return mView;
    }


    private void ini() {
        mManager = new DBManager(mContext);
        mManager.copyDBFile();

        SharedPreferences sp = mContext.getSharedPreferences("FWDID", Context.MODE_PRIVATE);
        if(sp!=null){
            mId = sp.getString("id", "");
        }

    }


    private void initData() {
        mAdapter = new FragmentTaskAdapter(getActivity(), mTaskList);
        mListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
        checkNum = 0;
        mCode = null;
    }

    private void initView() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                mListView.getItemAtPosition(position);
                FragmentTaskAdapter.ViewHolder holder = (FragmentTaskAdapter.ViewHolder) view.getTag();
                String code = "";
                if (mCode == null) {
                    mCode = code;
                    holder.cb.toggle();
                    mAdapter.getIsSelected().put(position, holder.cb.isChecked());
                } else if (mCode != null && !mCode.equals(code)) {
                    Toast.makeText(getActivity(), " 任务已经领取不能领取", Toast.LENGTH_SHORT).show();
                    return;
                } else {
                    holder.cb.toggle();
                    mAdapter.getIsSelected().put(position, holder.cb.isChecked());
                }

                // 调整选定条目
                if (holder.cb.isChecked() == true) {
                    checkNum++;
                } else {
                    checkNum--;
                }
                if (checkNum == 0) {
                    mCode = null;
                }
                if (checkNum > 0) {
                    mButLingqu.setEnabled(true);
                } else {
                    mButLingqu.setEnabled(false);
                }

            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (absListView.getLastVisiblePosition() == absListView.getCount() - 1 &&
                        i == SCROLL_STATE_IDLE) {
                    if (mTaskList.size() > mAdapter.showCount) {
                        mAdapter.showCount += 20;
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.butt_huoqu, R.id.but_lingqu})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.butt_huoqu:
               //连接服务端获取任务
                iniThread();
                break;
            case R.id.but_lingqu:
                saveTask(); //  获取选中任务   发消息给服务器 存入数据

                break;
        }
    }


    /**
     * 获取任务存入数据库
     **/
    private void saveTask() {
        List<String> mLstCode=new ArrayList<>();
        List<InventoryTaskSub> mTymeTaskSubList = new ArrayList<>();
        //获选中条目数据
        HashMap<Integer, Boolean> isSelected = mAdapter.getIsSelected();
        mListData = new ArrayList<>();
        Iterator iterator = isSelected.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry next = (Map.Entry) iterator.next();
            int key = (int) next.getKey();
            boolean value = (boolean) next.getValue();
            if (value) {
                mListData.add(mTaskList.get(key));
            }
        }


        //发消息给服务器更新 状态
        for (int i = 0; i < mListData.size(); i++) {
           mLstCode.add(mListData.get(i).getCode());
        }
        String postData = JSON.toJSONString(mLstCode);
        // 获取输入输出流
        // 启动线程 向服务器发送和接收信息
        new MyThread(postData).start();

        //根据任务单号 获取任务明细
        for (int i = 0; i < mListData.size(); i++) {
            int id = mListData.get(i).getId();
            mListData.get(i).setState("领取");
            for (int j = 0; j < mTaskSubList.size(); j++) {
                int cheadguid = mTaskSubList.get(j).getCheadguid();
                if (id == cheadguid) {
                    mTymeTaskSubList.add(mTaskSubList.get(j));
                }
            }
            mListData.get(i).setInventoryTaskSub(mTymeTaskSubList);
        }


        if (mListData != null && mListData.size() > 0) {
            //存入数据库
            int i = mManager.insertTaskData(mListData);
            if (i == 1) {
                mTaskList.clear();
                mTaskSubList.clear();
                mAdapter.setListDataBean(mTaskList);
                mAdapter.notifyDataSetChanged();
                Toast.makeText(mContext, "领取任务成功", Toast.LENGTH_SHORT).show();
            }
        }

    }

    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 66) {
                Bundle bundle = msg.getData();
                mMStr = bundle.getString("msg");
                if (mMStr != null && mMStr.length() > 0 && !mMStr.equals("失败")) {
                    Gson gson = new Gson();
                    SubInfo subInfo = gson.fromJson(mMStr, SubInfo.class);
                    mTaskList = subInfo.getTaskList();
                    mTaskSubList = subInfo.getTaskSubList();
                    if (mTaskList != null && mTaskList.size() > 0) {
                        initData();
                    }else {
                        Toast.makeText(mContext, "服务端异常", Toast.LENGTH_SHORT).show();
                    }
                }else {
                    Toast.makeText(mContext, "连接服务端异常", Toast.LENGTH_SHORT).show();
                }
            }else {
                Toast.makeText(mContext, "服务端异常", Toast.LENGTH_SHORT).show();
            }

        }
    };

    private void iniThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 定义消息
                Message msg = new Message();
                msg.what = 66;
                Bundle bundle = new Bundle();
                bundle.clear();
                try {
                    // 连接服务器 并设置连接超时为5秒
                    socket = new Socket();
                    socket.connect(new InetSocketAddress(mId, 30000), 1000);
                    BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // 读取发来服务器信息
                    String line = null;
                    buffer = "";
                    while ((line = bff.readLine()) != null) {
                        buffer = line + buffer;
                    }
                    bundle.putString("msg", buffer.toString());
                    msg.setData(bundle);
                    // 发送消息 修改UI线程中的组件
                    myHandler.sendMessage(msg);
                    // 关闭各种输入输出流
                    bff.close();
                    socket.close();
                } catch (SocketTimeoutException aa) {
                    // 连接超时 在UI界面显示消息
                    bundle.putString("msg", "失败");
                    msg.setData(bundle);
                    // 发送消息 修改UI线程中的组件
                    myHandler.sendMessage(msg);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    class MyThread extends Thread {
        public String txt1;

        public MyThread(String str) {
            txt1 = str;
        }

        @Override
        public void run() {
            // 定义消息
            Message msg = new Message();
            msg.what = 67;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {
                // 连接服务器 并设置连接超时为5秒
                socket = new Socket();
                socket.connect(new InetSocketAddress(mId, 30000), 1000);
                OutputStream ou = socket.getOutputStream();
                // 向服务器发送信息
                ou.write(txt1.getBytes("UTF-8"));
                ou.flush();
                bundle.putString("msg", buffer.toString());
                msg.setData(bundle);
                // 发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
                ou.close();
                socket.close();
            } catch (SocketTimeoutException aa) {
                // 连接超时 在UI界面显示消息
                bundle.putString("msg", "失败=======");
                msg.setData(bundle);
                // 发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
    }
}
